/*! 
 * jquery.ux.toast - v 1.0.0 - http://jquery-ux.com/
 * Copyright (c) 2010 Michael Helgeson, Three Dub Media
 * Open Source MIT License - http://jquery-ux.com/license 
 */
// Created: 2010-02-15 
// Updated: 2010-02-15
// REQUIRES: jquery 1.4+, jquery.ux

;(function( $ ){ // confine scope

$.ux( "toast", { // Register the PLUGIN... and public methods...
	version: "1.0.0",
	expose: "add", // + enable disable destroy
	defaults: {
		align: "right top",
		alignTo: window,
		insert: "append", // "prepend"
		duration: 2000 // milliseconds
		},
	create: function( elem, opts ){
		this.$toaster = $('<div/>').addClass( this.classify() )
			.bind("mouseover mouseout", $.proxy( this, "handler" ) );
		$( window ).bind("resize"+this.uxid+" scroll"+this.uxid, $.proxy( this, "align" ) );
		this.$hovered = $([]); // internal cache
		},
	destroy: function(){
		this.$toaster.remove();
		$( window ).unbind( this.uxid );
		},
	methods: {
		handler: function( ev ){ //console.log("handler ~ ", ev.type );
			// find the nearest message
			var $div = $( ev.target ).closest("."+ this.classify("message") );
			// validate the result
			if ( !$div.length ) return;
			// handle each event
			switch ( ev.type ){
				case "mouseover":
					this.pause( this.$hovered = $div );
					break;
				case "mouseout":
					this.timeout( this.$hovered );
					break;
				}
			},
		add: function( html ){ //console.log("add");
			var $div = $( html ).addClass( this.classify("message") );
			this.$toaster[ this.options.insert ]( $div );
			this.timeout( $div );
			this.show();
			},
		timeout: function( $div ){// console.log("timeout");
			var self = this;
			$div.data("toast.timer", setTimeout(function(){
				self.drop( $div );
				}, this.options.duration ));
			},
		pause: function( $div ){ //console.log("pause");
			if ( $div && $div.length ){
				clearTimeout( $div.data("toast.timer") );
				$div.stop( true );
				$div.css("opacity", 1 );
				}
			},	
		drop: function( $div ){ //console.log("drop");
			if ( $div && $div.length )
				$div.fadeOut( this.options.duration, $.proxy( $div, "remove" ) );
			},
		show: function(){ //console.log("show");
			this.$toaster.show().appendTo( document.body );
			this.align();
			},
		hide: function(){ //console.log("hide");
			this.$toaster.hide().detach();
			},
		align: function(){// console.log("align");
			this.$toaster.align( this.options.alignTo, this.options.align );
			}	
		}
	});

})( jQuery ); // secure the $ jQuery alias